package com.up.vms.interfaces.rest.security;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import com.up.vms.domain.module.UserDTO;
import com.up.vms.infrastructure.mvc.RespCode;
import com.up.vms.infrastructure.mvc.ReturnCode;
import com.up.vms.interfaces.rest.response.CommonResponse;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>
 * 自定义登录成功后的处理方式
 * </p>
 *
 */
@Slf4j
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        CommonResponse systemResponseMsg = new CommonResponse();
        systemResponseMsg.setRespCode(new RespCode(ReturnCode.SUCCESS));

        Object principal = authentication.getPrincipal();

        UserDTO userModel = ((UserContext) principal).getUserDTO();
        userModel.setPassword("");

        systemResponseMsg.setData(userModel);

        PrintWriter writer = httpServletResponse.getWriter();

        writer.write(JSON.toJSONString(systemResponseMsg));
    }
}